#!/usr/bin/env python3
# main.py
# 项目入口：初始化组件、启动服务器和UI
import sys
import threading
import logging
from PyQt5.QtWidgets import QApplication

from config import IF_VISUALIZE, LOG_LEVEL, LOG_FILE, DATA_ROOT
from core.server_core import MultiRobotServer
from policy.pursuit_policy import PursuitPolicy
from map_manager.map_manage import MapManager
from ui.main_window import PursuitGameUI

# 配置日志
# 替换 logging.basicConfig 部分为以下代码
file_handler = logging.FileHandler(LOG_FILE, encoding="utf-8")
file_handler.setLevel(getattr(logging, LOG_LEVEL))

console_handler = logging.StreamHandler()
console_handler.setLevel(getattr(logging, LOG_LEVEL))

logging.basicConfig(
    level=getattr(logging, LOG_LEVEL),
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        console_handler,
        file_handler,
    ],
)
logger = logging.getLogger(__name__)


def main():
    logger.info("程序启动...")
    # 初始化地图管理器
    map_manager = MapManager(logger)
    # 初始化策略
    policy = PursuitPolicy(map_manager, logger)
    # 初始化服务器
    server = MultiRobotServer(policy, map_manager, logger)
    # 启动服务器线程
    server_thread = threading.Thread(target=server.start, daemon=True)
    server_thread.start()
    logger.info("服务器线程启动")
    # 启动UI（如果启用）
    if IF_VISUALIZE:
        app = QApplication(sys.argv)
        ui = PursuitGameUI(server, logger)
        ui.show()
        logger.info("UI窗口启动")
        sys.exit(app.exec_())
    else:
        logger.info("Qt可视化窗口已禁用")
        try:
            while True:
                threading.Event().wait(0.05)
        except KeyboardInterrupt:
            logger.info("服务器已停止")
            if hasattr(server, "logbag_file"):
                server.logbag_file.close()


if __name__ == "__main__":
    main()
